class User < ActiveRecord::Base
  has_many :articles
  validates_presence_of :username
  validates_uniqueness_of :username
  
  attr_accessor :password_confirmation
  attr_accessor :password
  validates_confirmation_of :password
  validates_format_of :email, :with => /\b[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}\b/, :message => "wrong e-mail format"
  
  def validate
    errors.add_to_base("Missing password") if hashed_password.blank?
  end
  
  private
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt # 'wibble' makes it harder to guess
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  
  def password
    @password
  end
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
end
